package com.yixiaobai.swimming.service;

import com.yixiaobai.swimming.common.ResponseData;
import com.yixiaobai.swimming.dao.EmployerDao;
import com.yixiaobai.swimming.dto.request.AddEmployerReqDto;
import com.yixiaobai.swimming.dto.request.DeleteEmployerReqDto;
import com.yixiaobai.swimming.dto.request.RegisterReqDto;
import com.yixiaobai.swimming.entity.Employer;
import com.yixiaobai.swimming.error.ErrorCode;
import com.yixiaobai.swimming.util.CookieUtils;
import com.yixiaobai.swimming.util.PwdUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;

/**
 * @author yuyunlong
 * @date 2020/7/4 1:22 下午
 * @description
 */
@Service
@Slf4j
public class EmployerService {

    @Autowired
    private EmployerDao employerDao;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletResponse httpServletResponse;
    @Autowired
    private HttpServletRequest httpServletRequest;

    private final String DEFAULT_PWD = "123456";

    /**
     * 注册
     *
     * @param registerReqDto
     * @return
     */
    public ResponseData<String> register(RegisterReqDto registerReqDto) throws Exception {
        Employer data = employerDao.queryByUsername(registerReqDto.getUsername());
        if (Objects.nonNull(data)) {
            return ResponseData.buildErr(ErrorCode.USERNAME_EXIST_ERROR);
        }
        String password = registerReqDto.getPassword();
        String phone = registerReqDto.getPhone();
        if (password.length() < 6 || password.length() > 12) {
            return ResponseData.buildErr(ErrorCode.PARAM_ERROR);
        }
        if (!StringUtils.isNumeric(phone) && phone.length() != 11) {
            return ResponseData.buildErr(ErrorCode.PHONE_ERROR);
        }
        Employer phoneExist = employerDao.queryByPhone(phone);
        if (Objects.nonNull(phoneExist)) {
            return ResponseData.buildErr(ErrorCode.PHONE_EXIST_ERROR);
        }
        //加密密码
        password = PwdUtils.getSHA256EncryptStr(password);

        Employer employer = new Employer();
        employer.setUsername(registerReqDto.getUsername());
        employer.setPassword(password);
        employer.setRealname(registerReqDto.getRealName());
        employer.setPassword(password);
        employer.setPhone(phone);
        employer.setSex(registerReqDto.getSex());
        Date now = new Date();
        employer.setAddtime(now);
        Boolean insertResult = employerDao.insert(employer);
        log.info("新用户注册:{}", registerReqDto.toString());
        if (!insertResult) {
            return ResponseData.buildErr(ErrorCode.REGISTER_FAIL);
        }
        return ResponseData.build("注册成功");
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    public ResponseData<String> login(String username, String password) {
        String encryptPwd = PwdUtils.getSHA256EncryptStr(password);
        Employer result = employerDao.queryByUsername(username);
        if(Objects.isNull(result)){
            return ResponseData.buildErr(ErrorCode.USERNAME_NOT_EXIST_ERROR);
        }

        Date now = new Date();
        //用户名+时间戳，加密后生成token
        String token = PwdUtils.getSHA256EncryptStr(username + now.getTime());
        //放到redis中
        redisTemplate.opsForValue().set(username, token);
        String cache = (String) redisTemplate.opsForValue().get(username);
        log.info("缓存中数据,username:{},token:{}", username, cache);
        //放到cookie中
        CookieUtils.set(httpServletResponse, username, token);
        if (username.equals(result.getUsername()) && encryptPwd.equals(result.getPassword())) {
            return ResponseData.build("登录成功");
        }
        return ResponseData.buildErr(ErrorCode.LOGIN_FAIL_ERROR);
    }

    /**
     * 添加用户接口v1
     *
     * @param addEmployerReqDto
     * @return
     */
    public ResponseData<String> addEmployerV1(AddEmployerReqDto addEmployerReqDto) {
        String addUser = addEmployerReqDto.getAddUser();
        //从cookie获取token
        String token = CookieUtils.getValue(httpServletRequest, addUser);
        //从redis中取token
        String cacheToken = (String) redisTemplate.opsForValue().get(addUser);
        //redis中无token，表示未登陆
        if (Objects.isNull(cacheToken)) {
            return ResponseData.buildErr(ErrorCode.NOT_LOGIN_ERROR);
        }
        if (!cacheToken.equals(token)) {
            return ResponseData.buildErr(ErrorCode.TOKEN_ERROR);
        }
        //token一样时，进行下面的操作
        Integer uType = employerDao.queryUtypeByAddUser(addUser);
        if (uType != 0) {
            return ResponseData.buildErr(ErrorCode.PERMISSION_DENY_ERROR);
        }
        Employer usernameExist = employerDao.queryByUsername(addEmployerReqDto.getUsername());
        Employer phoneExist = employerDao.queryByPhone(addEmployerReqDto.getPhone());
        if (Objects.nonNull(usernameExist)) {
            return ResponseData.buildErr(ErrorCode.USERNAME_EXIST_ERROR);
        }
        if (Objects.nonNull(phoneExist)) {
            return ResponseData.buildErr(ErrorCode.PHONE_EXIST_ERROR);
        }
        String encryptPwd = PwdUtils.getSHA256EncryptStr(DEFAULT_PWD);
        Employer employer = new Employer();
        employer.setUsername(addEmployerReqDto.getUsername());
        employer.setRealname(addEmployerReqDto.getRealName());
        employer.setPassword(encryptPwd);
        employer.setPhone(addEmployerReqDto.getPhone());
        employer.setSex(addEmployerReqDto.getSex());
        employer.setUtype(1);
        employer.setAddtime(new Date());
        employer.setAdduser(addUser);
        try {
            employerDao.insert(employer);
            return ResponseData.build("添加用户成功");
        } catch (Exception e) {
            log.error("插入数据库失败", e);
        }
        return ResponseData.buildErr(ErrorCode.EXECUTE_FAIL);
    }

    public ResponseData<String> deleteEmployerV1(DeleteEmployerReqDto deleteEmployerReqDto){
        String deleteUser = deleteEmployerReqDto.getDeleteUser();
        //从cookie获取token
        String token = CookieUtils.getValue(httpServletRequest, deleteUser);
        //从redis中取token
        String cacheToken = (String) redisTemplate.opsForValue().get(deleteUser);
        //redis中无token，表示未登陆
        if (Objects.isNull(cacheToken)) {
            return ResponseData.buildErr(ErrorCode.NOT_LOGIN_ERROR);
        }
        if (!cacheToken.equals(token)) {
            return ResponseData.buildErr(ErrorCode.TOKEN_ERROR);
        }
        //token一样时，进行下面的操作
        Employer employer = employerDao.queryByUsername(deleteUser);
        if (0 != employer.getUtype()) {
            return ResponseData.buildErr(ErrorCode.PERMISSION_DENY_ERROR);
        }
        Employer usernameExist = employerDao.queryByUsername(deleteEmployerReqDto.getUsername());
        if (Objects.isNull(usernameExist)) {
            return ResponseData.buildErr(ErrorCode.USERNAME_NOT_EXIST_ERROR);
        }
        Integer result = employerDao.deleteEmployerByDeleteUser(deleteEmployerReqDto.getUsername());
        if(result > 0)
            return ResponseData.build("SUCESS");
        return ResponseData.buildErr(ErrorCode.EXECUTE_FAIL);
    }
}
